package com.lvyq.myplayer.net

import com.lvyq.myplayer.util.ThreadUtil
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

/**
 * 文件描述：NetManager 发送网络请求类
 * 作者：lvyq
 * 创建时间：2025-02-21
 * 修改时间：2025-02-21
 */
//单例
class NetManager private constructor(){

    val client by lazy { OkHttpClient()  }

    companion object{
       val manager by lazy { NetManager() }
    }


    /**
     * 发送网络请求
     */
    fun <RESPONSE> senRequest(req:MRequest<RESPONSE>){
        val path = req.url
        val reuqest = Request.Builder()
            .url(path)
            .get()
            .build()
        client.newCall(reuqest).enqueue(object : Callback {
            //子线程中调用
            override fun onFailure(call: Call, e: IOException) {
                //因此刷新控件
                ThreadUtil.runOnMainThread(object :Runnable{
                    override fun run() {
                        req.handler.onError(req.type,"获取数据失败")
                    }
                })
            }
            override fun onResponse(call: Call, response: Response) {
                var result = response.body?.string()

                var parseResult = req.parseResult(result)
                //刷新列表
                ThreadUtil.runOnMainThread(object:Runnable{
                    override fun run() {
                        //返回数据
                       req.handler.onSuccess(req.type,parseResult)
                    }
                })
            }
    })
}
}